package com.shouxin.attendance.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;

import com.shouxin.attendance.R;
import com.shouxin.attendance.utils.UIUtils;

/**
 * <p>Activity基类</p>
 * Created by Jiang on 2015/10/15.
 */
public abstract class BaseActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener, Handler.Callback {

	static final int SHOW_TOAST = 0x1000;

	static final int DIALOG_DISMISS = 0x1001;

	protected Context mContext;

	protected Toolbar mToolbar;

	protected Handler mHandler;

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
			case SHOW_TOAST:
				UIUtils.toast((String) msg.obj);
				break;
			case DIALOG_DISMISS:
				UIUtils.dismiss();
				break;
			default:
				break;
		}
		return true;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mContext = this;
		mHandler = new Handler(getMainLooper(), this);

		setContentView();
		initData();

		mToolbar = (Toolbar) findViewById(R.id.toolbar);
		if (mToolbar != null) {
			setSupportActionBar(mToolbar);
			mToolbar.setOnMenuItemClickListener(this);
			initToolbar();
		}

		initUIViews();
		bindEvents();
	}

	@Override
	public boolean onMenuItemClick(MenuItem item) {
		return false;
	}

	protected void initToolbar() {
		mToolbar.setNavigationIcon(R.mipmap.ic_back);
		mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	protected abstract void setContentView();

	protected abstract void initUIViews();

	protected abstract void initData();

	protected abstract void bindEvents();

	protected void NoConnectDialog(String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("提示");
		builder.setCancelable(true);
		builder.setMessage(message);
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				finish();
			}
		});
		builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				startActivity(new Intent(Settings.ACTION_SETTINGS));
			}
		});
		builder.show();
	}

	protected void setTitle(String title) {
		if (getSupportActionBar() != null) {
			getSupportActionBar().setTitle(title);
		}
	}
}
